const mysql = require('mysql2/promise');
const dotenv = require('dotenv');

dotenv.config({ path: '.env.local' });

async function testDatabaseAndApi() {
  try {
    // 测试数据库连接
    console.log('测试数据库连接...');
    console.log('数据库配置:', {
      host: process.env.DB_HOST || 'rm-bp14wd51i709c3z79ho.mysql.rds.aliyuncs.com',
      user: process.env.DB_USER || 'root',
      database: process.env.DB_NAME || 'xiaoyoubao',
      port: Number(process.env.DB_PORT) || 3306
    });
    
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'rm-bp14wd51i709c3z79ho.mysql.rds.aliyuncs.com',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || 'Ircnjfdhnvxwz@123',
      database: process.env.DB_NAME || 'xiaoyoubao',
      port: Number(process.env.DB_PORT) || 3306
    });
    
    console.log('数据库连接成功');
    
    // 检查enterprise_policies表是否存在
    try {
      const [tables] = await connection.execute('SHOW TABLES LIKE "enterprise_policies"');
      if (tables.length === 0) {
        console.error('enterprise_policies表不存在');
      } else {
        console.log('enterprise_policies表存在');
        
        // 查询数据
        const [rows] = await connection.execute('SELECT COUNT(*) as count FROM enterprise_policies');
        console.log(`enterprise_policies表中有${rows[0].count}条记录`);
        
        // 获取表结构
        const [columns] = await connection.execute('SHOW COLUMNS FROM enterprise_policies');
        console.log('enterprise_policies表结构:');
        console.log(columns);
        
        // 获取示例数据
        const [data] = await connection.execute('SELECT * FROM enterprise_policies LIMIT 1');
        console.log('示例数据:');
        console.log(data);
      }
    } catch (err) {
      console.error('查询表结构失败:', err);
    }
    
    // 模拟API查询
    try {
      const whereClause = '1=1';
      const params = [];
      const limit = 10;
      const offset = 0;
      
      const policiesQuery = `
        SELECT 
          id, title, summary, source, publish_date, 
          original_url, category, tags, 
          key_points, requirements, created_at
        FROM enterprise_policies
        WHERE ${whereClause}
        ORDER BY publish_date DESC, id DESC
        LIMIT ? OFFSET ?
      `;
      
      const [policies] = await connection.execute(policiesQuery, [...params, limit, offset]);
      console.log('模拟API查询结果:');
      console.log(policies);
      
      // 测试JSON.parse逻辑
      const formattedPolicies = policies.map(policy => {
        try {
          return {
            id: policy.id,
            title: policy.title,
            summary: policy.summary,
            source: policy.source,
            publishDate: policy.publish_date ? new Date(policy.publish_date).toISOString().split('T')[0] : null,
            url: policy.original_url,
            category: policy.category,
            tags: policy.tags ? policy.tags.split(',') : [],
            keyPoints: policy.key_points ? JSON.parse(policy.key_points) : [],
            requirements: policy.requirements ? JSON.parse(policy.requirements) : [],
            createdAt: policy.created_at
          };
        } catch (err) {
          console.error(`格式化政策ID ${policy.id} 时出错:`, err);
          console.log('问题数据:', {
            key_points: policy.key_points,
            requirements: policy.requirements
          });
          return null;
        }
      }).filter(Boolean);
      
      console.log('格式化后的政策数据:');
      console.log(formattedPolicies);
    } catch (err) {
      console.error('模拟API查询失败:', err);
    }
    
    await connection.end();
  } catch (error) {
    console.error('测试失败:', error);
  }
}

testDatabaseAndApi(); 